<?php

/*罚款单 2017/2/16 孟凡涛*/

namespace Admin\Model;
use Think\Model;
class FineModel extends Model {

    /*获取罚款单信息 */
    public function getFine($GET,$isAdmin) {

		$r = array('d'=>NULL,'i'=>'','r'=>0);
        // $GET = $GET;
        $isAdmin = $isAdmin;
        $dlist = array();

        if($GET['sales_name']) {

            $where = array();

            $start_time = strtotime($GET['start_time'] );
            $end_time = strtotime($GET['end_time'] );
            if($GET['start_time'] && $GET['end_time'] && $GET['start_time'] != 'undefined' && $GET['end_time'] != 'undefined') {
                $where['b.pub_time'] = array('BETWEEN',array(date('Y-m-d 00:00:00', $start_time ),date('Y-m-d 23:59:59', $end_time )));
            } else if($GET['start_time'] && $GET['start_time'] != 'undefined') {
                $where['b.pub_time'] = array('EGT', date('Y-m-d 00:00:00', $start_time ));
            } else if($GET['end_time'] && $GET['end_time'] != 'undefined') {
                $where['b.pub_time'] = array('ELT',date('Y-m-d 23:59:59', $end_time ));
            }

            if($GET['sales_name'])            $where['c.nickname'] = array('like','%'.$GET['sales_name'].'%'); 
            $where['b.fine_type'] = 1;
            $where['b.is_delete'] = 0;
            $where['a.is_delete'] = 0;
            $where['_string'] = '1=1';

            $cnt = M()->field("a.fine_id")
                        ->table('fine_user as a')
                        ->join('fine as b on b.fine_id = a.fine_id')
                        ->join('user as c on c.user_id = a.sales_id')
                        ->where( $where)
                        ->group('a.fine_id')
                        ->count();


            $psize = $GET['psize'];
            $Page = new \Common\ORG\Page( $cnt, $psize);

            $dlist1 = M()->field("a.fine_id")
                        ->table('fine_user as a')
                        ->join('fine as b on b.fine_id = a.fine_id')
                        ->join('user as c on c.user_id = a.sales_id')
                        ->where( $where)
                        ->order('b.pub_time desc')
                        ->group('a.fine_id')
                        ->limit($Page->firstRow.','.$Page->listRows )
                        ->select();
            
            $arrFine = array();
            foreach($dlist1 as $key=>$value){
                $arrFine[$key] = $value['fine_id'];
            }
            
            /*********************************************************************************************/
            if( $arrFine) {
                $where1 = array();
                $where1['a.fine_id'] = array('IN',$arrFine);
                $where1['a.is_delete'] = 0;
                $where1['_string'] = '1=1';

                $dlist = M()->field('a.*,b.*')
                            ->table('fine as a')
                            ->join('sys_param_detail as b on b.sys_param_detail_id = a.theme')
                            ->where($where1)
                            ->order('pub_time desc')
                            ->select();
                            
                if( $dlist) {
                    foreach($dlist as &$value){ 
                        $value['fine_user'] = M()->field("a.*,b.nickname as name,b.*,c.sector_name,d.nickname as sales_managername,
                                                    CASE WHEN a.fine_type = 1 THEN a.fine_mount
                                                         WHEN a.fine_type = 2 THEN a.fine_remark
                                                         ELSE NULL END AS fine_content
                                                    ")
                                                ->table('fine_user as a')
                                                ->join('user as b on b.user_id = a.sales_id')
                                                ->join('sector as c on c.sector_id = b.sector_id')
                                                ->join('user as d on d.user_id = a.sales_manager')
                                                ->where("a.fine_id = %d",$value['fine_id'])
                                                ->order('a.fine_user_id asc')
                                                ->select();
                    }
                }
            }

        } else {

            $where = array();     
            $start_time = strtotime($GET['start_time'] );
            $end_time = strtotime($GET['end_time'] );
            if($GET['start_time'] && $GET['end_time'] && $GET['start_time'] != 'undefined' && $GET['end_time'] != 'undefined') {
                $where['a.pub_time'] = array('BETWEEN',array(date('Y-m-d 00:00:00', $start_time ),date('Y-m-d 23:59:59', $end_time )));
            } else if($GET['start_time'] && $GET['start_time'] != 'undefined') {
                $where['a.pub_time'] = array('EGT', date('Y-m-d 00:00:00', $start_time ));
            } else if($GET['end_time'] && $GET['end_time'] != 'undefined') {
                $where['a.pub_time'] = array('ELT',date('Y-m-d 23:59:59', $end_time ));
            }

            $where['a.fine_type'] = 1;
            $where['a.is_delete'] = 0;
            $where['_string'] = '1=1';

            $cnt = M() ->field('a.*,b.*')
                        ->table('fine as a')
                        ->join('sys_param_detail as b on b.sys_param_detail_id = a.theme')
                        ->where( $where)
                        ->count();

            $psize = $GET['psize'];
            $Page = new \Common\ORG\Page( $cnt, $psize);

            $dlist = M() ->field('a.*,b.*')
                        ->table('fine as a')
                        ->join('sys_param_detail as b on b.sys_param_detail_id = a.theme')
                        ->where( $where)
                        ->order('a.pub_time desc')
                        ->limit($Page->firstRow.','.$Page->listRows )
                        ->select();
                        
            if( $dlist) {
                foreach($dlist as &$value){ 
                    $wheres['a.fine_id'] = $value['fine_id'];
                    $where['a.is_delete'] = 0;
                    $value['fine_user'] = M()->field("a.*,b.nickname as name,b.*,c.sector_name,d.nickname as sales_managername,
                                                CASE WHEN a.fine_type = 1 THEN a.fine_mount
                                                        WHEN a.fine_type = 2 THEN a.fine_remark
                                                        ELSE NULL END AS fine_content
                                                ")
                                            ->table('fine_user as a')
                                            ->join('user as b on b.user_id = a.sales_id')
                                            ->join('sector as c on c.sector_id = b.sector_id')
                                            ->join('user as d on d.user_id = a.sales_manager')
                                            ->where($wheres)
                                            ->order('a.fine_user_id asc')
                                            ->select();
                }
            }
        }

        if( $dlist ){
            $r['r'] = 1;
            $r['d'] = $dlist;
            $r['pall'] =  $Page->getTotalPages();
            $r['p'] = $Page->nowPage;
            $r['psize'] = $psize;
        }else{
            $r['m'] = '罚款单信息获取失败';
        }
        return $r;
    }

    /*添加罚款单信息*/
	public function addFine($POST) {
        $uinfo = UserModel::loadFromSession();
        $r = array('r'=>0,'d'=>NULL,'m'=>'OK');

        $POST_FINE = $POST['fine'];
        $POST_USER = $POST['fine_user'];
        $d = array();
        if( $POST_FINE['title'])             $d['title'] = $POST_FINE['title'];
        if( $POST_FINE['theme'])             $d['theme'] = $POST_FINE['theme'];
        if( $POST_FINE['show_way'])          $d['show_way'] = $POST_FINE['show_way'];
        if( $POST_FINE['reply_action'])      $d['reply_action'] = $POST_FINE['reply_action'];
        if( $POST_FINE['fine_num'])          $d['fine_num'] = $POST_FINE['fine_num'];
        if( $POST_FINE['description'])       $d['description'] = $POST_FINE['description'];

        /*默认字段*/
        $d['fine_type'] = 1;
        $d['status'] = 0;
        $d['creator'] = $uinfo['user_id'];
        $d['show_way'] = '';
        $d['pub_time'] = date('Y-m-d H:i:s');
        $d['update_time'] = date('Y-m-d H:i:s');
        
        $addID = $this->data($d)->add();
        $addUser = array();
        if( $addID) {
            $addUser = $this->addFineUser($addID, $POST_USER);
        }
        if( $addID) {
            $r['r'] = 1;
            $r['d'] = $addID;
        }else {
            $r['m'] = '罚款单信息添加失败';
        }
        return $r;
    }

    /*添加罚款单关联人*/
    public function addFineUser($fine_id, $POST_USER) {
        $r = array('r'=>0,'d'=>NULL,'m'=>'OK');

        $POST_USER = $POST_USER;
        $fine_id = $fine_id;
        $MUser = M('user','fine_');

        foreach($POST_USER as &$value){
            $value['fine_id'] = $fine_id;
            $addID = $MUser->data($value)->add();
        }
        if( $addID) {
            $r['r'] = 1;
            $r['d'] = $addID;
        }else {
            $r['m'] = '罚款单关联人信息添加失败';
        }
        return $r;
    }

    /*更新罚款单信息*/
	public function updateFine($POST) {
        $uinfo = UserModel::loadFromSession();
        $r = array('r'=>0,'d'=>NULL,'m'=>'OK');

        $POST_FINE = $POST['fine'];
        $POST_USER = $POST['fine_user'];
        $d = array();
        if( $POST_FINE['title'])             $d['title'] = $POST_FINE['title'];
        if( $POST_FINE['theme'])             $d['theme'] = $POST_FINE['theme'];
        if( $POST_FINE['show_way'])          $d['show_way'] = $POST_FINE['show_way'];
        if( $POST_FINE['reply_action'])      $d['reply_action'] = $POST_FINE['reply_action'];
        if( $POST_FINE['fine_num'])          $d['fine_num'] = $POST_FINE['fine_num'];
        if( $POST_FINE['description'])       $d['description'] = $POST_FINE['description'];

        /*默认字段*/
        $d['update_time'] = date('Y-m-d H:i:s');
        
        $updateID = $this->where("fine_id=%d",$POST_FINE['fine_id'])->data($d)->save();
        $dlist = array();
        if( $updateID) {
            $dlist = $this->updateUser($POST_FINE['fine_id'],$POST_USER);
        }
        if( $updateID) {
            $r['r'] = 1;
            $r['d'] = $d;
        }else {
            $r['m'] = '罚款单信息更新失败';
        }
        return $r;
    }

    /*更新罚款单关联人*/
    public function updateUser($fine_id,$POST_USER) {
        $r = array('r'=>0,'d'=>NULL,'m'=>'OK');

        $POST_USER = $POST_USER;

        $MUser = M('user','fine_');
        $fine_id = $fine_id;
        $delID = $MUser->where("fine_id=%d",$fine_id)->delete();

        foreach($POST_USER as $key=>$value){
            $d[$key]['fine_id'] = $fine_id;
            $d[$key]['fine_type'] = $value['fine_type'];
            if($value['fine_type'] == 1) 
                $d[$key]['fine_mount'] = $value['fine_mount']; 
            if($value['fine_type'] == 2) 
                $d[$key]['fine_remark'] = $value['fine_remark']; 
            $d[$key]['sales_id'] = $value['sales_id']; 
            $d[$key]['sales_sector'] = $value['sales_sector']; 
            $d[$key]['sales_manager'] = $value['sales_manager']; 
            $d[$key]['sales_subcompany'] = $value['sales_subcompany']; 
            $addID = $MUser->data($d[$key])->add();
        }
        if( $addID) {
            $r['r'] = 1;
            $r['d'] = $addID;
        }else {
            $r['m'] = '罚款单关联人信息更新失败';
        }
        return $r;
    }

    /*删除罚款单信息*/
	public function delFine($POST) {
        $POST = $POST;
        $d = array();
        $d['is_delete'] = 1;
        $delID1 = $this->where("fine_id=%d",$POST['fine_id'])->save($d);
        $delID2 = M('user','fine_')->where("fine_id=%d",$POST['fine_id'])->save($d);
        if( $delID1) {
            $r['r'] = 1;
            $r['d'] = $POST;
        }else {
            $r['m'] = '罚款单信息删除失败';
        }
        return $r;
    }

    /*根据部门ID获取员工信息*/
	public function getUserByID($sector_id) {
		$r = array('d'=>NULL,'i'=>'','r'=>0);

        $MSector = M('\Admin\Model\GoalsModel:Sector');
        $id = $sector_id;
        if(!$sector_id) {
            $dlist = M('sector')->field('sector_id')->where("parent_company=%d",0)->find();
            $id = $dlist['sector_id'];
            $r['m'] = $id;
        }

		$arr = $MSector->getChild($id);
        if($arr) {
            //获取权限个人
            $whereUser = array();
            $whereUser['a.sector_id'] = array('IN',$arr);
            $arrUser = M() ->field('a.user_id,a.nickname,b.sector_id as sales_sector,b.parent_company,b.is_subcompany,c.user_id as manager_id,c.nickname as manager_name')
                            ->table('user as a')
                            ->join('LEFT JOIN sector b on b.sector_id = a.sector_id')
                            ->join('LEFT JOIN user c on c.user_id = b.manager_id')
                            ->where($whereUser)
                            ->select();

            if( $arrUser ){
                $r['r'] = 1;
                $r['d'] = $arrUser;
            }else{
                $r['m'] = '员工信息获取失败';
            }
        }
        return $r;
    }

    /*获取违规系统参数表*/
	public function getSysParam($key_name) {
        $r = array('r'=>0,'d'=>NULL,'m'=>'OK');

        $dlist = M() ->field("a.sys_param_id,b.sys_param_detail_id,b.detail_name")
                        ->table('sys_param as a')
                        ->join('sys_param_detail as b on b.sys_param_id = a.sys_param_id')
                        ->where("a.key_name='%s'",$key_name)
                        ->order('b.detail_order asc')
                        ->select();

        if( $dlist) {
            $r['r'] = 1;
            $r['d'] = $dlist;
        } else {
            $r['m'] = '违规原因的系统参数获取失败';
        }
        return $r;
    }

    //wjl 20170718添加
    public function hrdadd( $data , $userid) {
        $rback = array('rcode'=>0, 'data'=>null, 'msg'=>'null');
        $is_date = strtotime($data['punish_date']) ? true : false;
        if (!$is_date) {
            $rback['msg'] = '日期格式不正确';
            return $rback;
        }
        if (!is_numeric($data['punish_type']) or $data['punish_type'] == '-1') {
            $rback['msg'] = '没有选择类别';
            return $rback;
        }
        if (!is_numeric($data['punish_class']) or $data['punish_class'] == '-1') {
            $rback['msg'] = '没有选择分类';
            return $rback;
        }
        $strid = $data['user_id'];
        if (strlen($strid) < 1) {
            $rback['msg'] = '没有选择工号或姓名';
            return $rback;
        }
        $spuinfo = explode(',', $strid);
        $finedata = array();
        $fineuserdata = array();
        $where = array();
        $uwhere = array();

        if (count($spuinfo) > 0) {
            if (strlen($data['punish_reason']) > 50) {
                $data['punish_reason'] = substr($data['punish_reason'], 0, 50);
            }
            if (strlen($data['punish_clsay']) > 50) {
                $data['punish_clsay'] = substr($data['punish_clsay'], 0, 50);
            }
            if (strlen($data['punist_beizhu']) > 200) {
                $data['punist_beizhu'] = substr($data['punist_beizhu'], 0, 200);
            }
            $finedata['pub_time'] = $data['punish_date'];
            $finedata['hr_fine_type'] = $data['punish_type'];
            $finedata['description'] = $data['punish_reason'];
            $finedata['remark'] = $data['punist_beizhu'];
            $finedata['fine_type'] = 3; //'人事惩罚'
            $finedata['creator'] = $userid;
            $finedata['update_time'] = date('Y-m-d H:i:s');

            //已存在判断
            // $ishave = $this->where( $where )->find();
            //if (!$ishave) {
            // }else{
            //     $rback['msg'] = '此罚单已存在';
            //     return $rback;
            // }

            $fineid = $this->add( $finedata );
            if ($fineid) {
                $fineuserdata['fine_id'] = $fineid;
                $fineuserdata['fine_type'] = $data['punish_class'];
                $fineuserdata['fine_remark'] = $data['punish_clsay'];
                $fineuser = M('fine_user');
                for ($i=0; $i < count($spuinfo); $i++) { 
                    $uvalue = explode('_', $spuinfo[$i]);
                    if (count($uvalue) == 4) {
                        $fineuserdata['sales_id'] = $uvalue[0];
                        $fineuserdata['sales_sector'] = $uvalue[1];
                        $fineuserdata['sales_role'] = $uvalue[2];
                        $fineuserdata['sales_exstatus'] = $uvalue[3];
                        //uwhere                        
                        $uwhere['fine_id'] = $fineid;
                        $uwhere['sales_id'] = $uvalue[0];
                        $uwhere['fine_type'] = $data['punish_class'];
                        $ufine = $fineuser->where( $uwhere )->find();
                        if (!$ufine) {
                            $fineuser->add( $fineuserdata );
                        }
                    }
                }
                $rback['rcode'] = 1;
                $rback['msg'] = '添加成功';
            }else{
                $rback['msg'] = '很抱歉，添加事件失败';
            }
        }
        return $rback;
    }    
    //编辑
    public function hrdsave( $data ){
        $rback = array('rcode'=>0, 'data'=>null, 'msg'=>'');
        if (!is_numeric($data['fine_id'])) {
            $rback['msg'] = '事件id参数错误';
            return $rback;
        }
        if (!is_numeric($data['sales_id'])) {
            $rback['msg'] = '用户id参数错误';
            return $rback;
        }
        $is_date = strtotime($data['pub_time']) ? true : false;
        if (!$is_date) {
            $rback['msg'] = '日期格式不正确';
            return $rback;
        }
        if (!is_numeric($data['hr_fine_type']) or $data['hr_fine_type'] == '-1') {
            $rback['msg'] = '没有选择类别';
            return $rback;
        }
        if (!is_numeric($data['fine_type']) or $data['fine_type'] == '-1') {
            $rback['msg'] = '没有选择分类';
            return $rback;
        }        
        if (strlen($data['description']) > 50) {
            $data['description'] = substr($data['description'], 0, 50);
        }
        if (strlen($data['fine_remark']) > 50) {
            $data['fine_remark'] = substr($data['fine_remark'], 0, 50);
        }
        if (strlen($data['remark']) > 200) {
            $data['remark'] = substr($data['remark'], 0, 200);
        }
        $finedata = array();
        $fineuserdata = array();
        $where = array();
        //事件
        $finedata['fine_id'] = $data['fine_id'];
        $finedata['hr_fine_type'] = $data['hr_fine_type'];
        $finedata['description'] = $data['description'];
        $finedata['pub_time'] = $data['pub_time'];
        $finedata['remark'] = $data['remark'];
        if ($this->save($finedata)) {
            $rback['rcode'] = 1;
            $rback['msg'] = '事件编辑成功';
        }else{
            $rback['msg'] = '编辑事件失败';
        }
        //人员
        $fineuserdata['fine_type'] = $data['fine_type'];
        $fineuserdata['fine_remark'] = $data['fine_remark'];
        //
        $where['fine_id'] = $data['fine_id'];
        $where['sales_id'] = $data['sales_id'];
        $fineuser = M('Fine_user');
        if ($fineuser->where( $where )->save($fineuserdata) ) {
            $rback['rcode'] = 1;
            $rback['msg'] = '编辑成功';
        }
        return $rback;
    }


}